package com.yzpc.controller;

import com.yzpc.entity.User;
import com.yzpc.service.IUserService;
import com.yzpc.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 编写处理用户登录的接口
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(@RequestBody User user) {
        User u = userService.login(user);
        if(u != null) {
            return R.success("登录成功", null);
        } else {
            return R.error("登录失败", null);
        }
    }
    @GetMapping("/{userId}")
    @ResponseBody
    public R getInfo(@PathVariable Integer userId) {
        return R.success(null, userService.findUserById(userId));
    }
    @GetMapping("name/{userName}")
    @ResponseBody
    public R getInfo(@PathVariable String userName) {
        return R.success(null, userService.findUserByName(userName));
    }
    @GetMapping("/list")
    @ResponseBody
    public R list(User user) {
        return R.success(null, userService.findUserList(user));
    }

    @PostMapping("/add")
    @ResponseBody
    public R add(@RequestBody User user) {
        int rtn = userService.insertUser(user);
        if(rtn > 0) {
            return R.success();
        } else {
            return R.error();
        }
    }
    @PutMapping("/edit")
    @ResponseBody
    public R edit(@RequestBody User user) {
        int rtn = userService.updateUserById(user);
        if(rtn > 0) {
            return R.success();
        } else {
            return R.error();
        }
    }
    @PutMapping("/editByName")
    @ResponseBody
    public R editByName(@RequestBody User user) {
        int rtn = userService.updateUserByName(user);
        if(rtn > 0) {
            return R.success();
        } else {
            return R.error();
        }
    }
    @DeleteMapping("/{userId}")
    @ResponseBody
    public R delete(@PathVariable Integer userId) {
        userService.deleteUserById(userId);
        return R.success();
    }
    @DeleteMapping("name/{userName}")
    @ResponseBody
    public R delete(@PathVariable String userName) {
        userService.deleteUserByName(userName);
        return R.success();
    }
}
